package edu.hgnc.controller.controllerAdvice;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ControllerAdviceController {

	private static Log log = LogFactory.getLog(ControllerAdviceController.class);

//	 全局异常处理
// 	@ExceptionHandler(Exception.class)
// 	public ModelAndView customerException(Exception e){
// 		ModelAndView mv = new ModelAndView();
// 		mv.addObject("message",e.getMessage());
// 		mv.setViewName("myError");
// 		// 发生了异常
// 		log.debug("发生异常了~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
// 		return mv;
// 	}

	//	 全局异常处理
	@ExceptionHandler(HttpMessageNotWritableException.class)
	public ModelAndView customerException(Exception e){
		ModelAndView mv = new ModelAndView();
		mv.addObject("message",e.getMessage());
		mv.setViewName("myError");
		// 发生了异常
		log.debug("发生异常了~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		return mv;
	}

//	 全局数据绑定
	@ModelAttribute(name = "md")
	public Map<String,Object> myData(){
		HashMap<String, Object> map = new HashMap<>();
		map.put("age",99);
		map.put("gender","男");
		return map;
	}

	@InitBinder("a")
	public void a(WebDataBinder binder){
		binder.setFieldDefaultPrefix("a.");
	}
	@InitBinder("b")
	public void b(WebDataBinder binder){
		binder.setFieldDefaultPrefix("b.");
	}
}
